package com.solution.admin.auth.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.solution.admin.auth.constants.AuthConstants;
import com.solution.admin.auth.entity.ResourceEntity;
import com.solution.admin.auth.entity.RoleEntity;
import com.solution.admin.auth.service.ResourceService;
import com.solution.admin.auth.service.RoleService;
import com.solution.common.controller.BaseController;
import com.solution.common.utils.string.StringUtil;

/**
 * @author zhuoyu
 * @date 2017年4月10日 下午4:37:50
 */
@RequestMapping("/resource")
@Controller
public class ResourceController extends BaseController {
	@SuppressWarnings("unused")
	private Logger logger = LoggerFactory.getLogger(ResourceController.class);

	@Autowired
	private ResourceService resourceService;

	@Autowired
	private RoleService roleService;

	/**
	 * 资源管理主页面
	 * 
	 * @author: solin
	 * @date: 2017年4月26日 下午3:54:20
	 * @param request
	 * @return
	 */
	@RequestMapping("/listResourcePage")
	public ModelAndView toResourceListPage(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("auth/resource/resource_list");
		return mav;
	}

	/**
	 * 修改
	 * 
	 * @param request
	 * @param resourceEntity
	 * @return
	 * @author zhuoyu
	 * @date 2017年4月10日 下午5:36:39
	 * @modify solin <2017年4月27日 下午1:36:39>
	 */
	@RequestMapping("/updateResource")
	@ResponseBody
	public Map<String, Object> updateResource(HttpServletRequest request, ResourceEntity resourceEntity) {
		Map<String, Object> result = new HashMap<String, Object>();
		resourceEntity.setModifier(getUserCode());
		resourceEntity.setModifyTime(new Date());
		int count = resourceService.updateResource(resourceEntity);
		if (count > 0) {
			result.put("code", AuthConstants.EDIT_RESULT.SUCCESS.getCode());
			result.put("msg", AuthConstants.EDIT_RESULT.SUCCESS.getMsg());
			return result;
		} else {
			result.put("code", AuthConstants.EDIT_RESULT.FAILED.getCode());
			result.put("msg", AuthConstants.EDIT_RESULT.FAILED.getMsg());
			return result;
		}

	}

	/**
	 * 修改
	 * 
	 * @param request
	 * @param resourceEntity
	 * @return
	 * @author zhuoyu
	 * @date 2017年4月10日 下午5:36:39
	 */
	@RequestMapping("/updateResourceStatus")
	@ResponseBody
	public int updateResourceStatus(HttpServletRequest request) {
		String id = request.getParameter("id");
		String status = request.getParameter("status");
		ResourceEntity resource = resourceService.getResourceById(Long.valueOf(id));
		// 修改版本
		resource.setVersion(resource.getVersion() + 1);
		resource.setStatus(Integer.valueOf(status));
		resource.setModifier(getUserCode());
		resource.setModifyTime(new Date());
		int count = resourceService.updateResource(resource);
		return count;

	}

	/**
	 * 删除
	 * @param request
	 * @return
	 * @author zhuoyu
	 * @date 2017年4月10日 下午5:16:37
	 * @modify <scy> <2017年4月10日 下午5:16:37>
	 */
	@RequestMapping("/deleteResource")
	@ResponseBody
	public int deleteResource(HttpServletRequest request) {
		String delId = request.getParameter("delId");
		if (delId == null) {
			return 0;
		}
		return resourceService.deleteResource(Long.valueOf(delId));
	}

	/**
	 * 查询详细
	 * @param request
	 * @return
	 * @author zhuoyu
	 * @date 2017年4月10日 下午5:33:31
	 * @modify <scy> <2017年4月10日 下午5:33:31>
	 */
	@RequestMapping("/getResourceById")
	@ResponseBody
	public ResourceEntity getResourceById(HttpServletRequest request) {
		String id = request.getParameter("id");
		if (id == null) {
			return null;
		}
		return resourceService.getResourceById(Long.valueOf(id));
	}

	/**
	 * 以树形式返回组织列表
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/getResourceForTree")
	@ResponseBody
	public List<ResourceEntity> getResourceForTree(HttpServletRequest request) {
		return resourceService.getResourceForTree();
	}

	/**
	 * 取得所有资源列表
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("getResourceList")
	@ResponseBody
	public List<ResourceEntity> getResourceList(HttpServletRequest request) {
		List<ResourceEntity> list = resourceService.resourceList();
		return list;
	}

	/**
	 * 跳转添加
	 * 
	 * @param request
	 * @return
	 * @author zhuoyu
	 * @date 2017年4月18日 下午5:55:11
	 */
	@RequestMapping("/toAddResource")
	public ModelAndView toAddResource(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("auth/resource/resource_add");
		return mav;
	}

	/**
	 * 跳转修改
	 * 
	 * @param request
	 * @return
	 * @author zhuoyu
	 * @date 2017年4月18日 下午5:55:11
	 */
	@RequestMapping("/toEditResource")
	public ModelAndView toEditResource(HttpServletRequest request) {
		String id = request.getParameter("id");
		ModelAndView mav = new ModelAndView();
		ResourceEntity resourceEntity = resourceService.getResourceById(Long.valueOf(id));
		if (resourceEntity.getParentId() != null) {
			mav.addObject("resourceOld", resourceService.getResourceById(Long.valueOf(resourceEntity.getParentId())));
		}
		mav.setViewName("auth/resource/resource_edit");
		mav.addObject("resource", resourceEntity);
		return mav;
	}

	/**
	 * 添加资源
	 * 
	 * @param request
	 * @param resourceEntity
	 * @return
	 * @author zhuoyu
	 * @date 2017年4月20日 下午7:45:10
	 * @modify solin 2017/04/27 16:00
	 */
	@RequestMapping("/addResource")
	@ResponseBody
	public Map<String, Object> addResource(HttpServletRequest request, ResourceEntity resourceEntity) {
		Map<String, Object> result = new HashMap<String, Object>();
		resourceEntity.setCreater(getUserCode());
		resourceEntity.setCreateTime(new Date());
		if (resourceEntity.getParentId() == null || resourceEntity.getParentId() == "") {
			resourceEntity.setParentId("0");
		}
		resourceEntity.setModifyTime(new Date());
		Long count = resourceService.insertResource(resourceEntity);
		if (count > 0) {
			result.put("code", AuthConstants.ADD_RESULT.SUCCESS.getCode());
			result.put("msg", AuthConstants.ADD_RESULT.SUCCESS.getMsg());
			return result;
		} else {
			result.put("code", AuthConstants.ADD_RESULT.FAILED.getCode());
			result.put("msg", AuthConstants.ADD_RESULT.FAILED.getMsg());
			return result;
		}
	}

	/**
	 * 取得某经销商角色的可用资源列表
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/getRoleResourceList")
	@ResponseBody
	public String getRoleResourceList(HttpServletRequest request) {
		String roleIdStr = request.getParameter("roleId");
		Long roleId = 0L;
		JSONArray nodes = new JSONArray();
		JSONObject root = new JSONObject();
		root.put("id", 0);
		root.put("resourceName", "全部资源");
		root.put("parentId", -1);
		root.put("checked", false);
		nodes.add(root);

		if (StringUtil.isNotNull(roleIdStr) && StringUtil.isNotEmpty(roleIdStr)) {
			roleId = Long.parseLong(roleIdStr);
		}

		List<ResourceEntity> resList = this.resourceService.getRoleResourceList( roleId);
		if (resList != null) {
			if (resList.size() > 0) {
				for (ResourceEntity res : resList) {
					JSONObject node = new JSONObject();
					node.put("id", res.getId());
					node.put("resourceName", res.getResourceName());
					node.put("parentId", res.getParentId());
					node.put("checked", res.getChecked().equals("1"));
					nodes.add(node);
				}
			}
		}
		resList = null;

		return nodes.toJSONString();
	}

	/**
	 * 更新某经销商角色的可用资源列表（重新授权）
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/updateRoleResource")
	@ResponseBody
	public Map<String, Object> updateRoleResource(HttpServletRequest request) {
		Map<String, Object> result = new HashMap<String, Object>();
		Long roleId = Long.valueOf(request.getParameter("roleId"));
		String resourceIds = request.getParameter("resourceIds");
		String roleName = request.getParameter("roleName");
		String roleIntro = request.getParameter("roleIntro");
		//将[1,3,4]json对象解析成 List<String>
		List<String> resIds = JSONArray.parseArray(resourceIds, String.class);
		RoleEntity role = new RoleEntity();
		role.setId(roleId);
		role.setRoleName(roleName);
		role.setRoleIntro(roleIntro);
		role.setStatus(AuthConstants.ROLE_STATUS.ENABLED.getId());
		// 修改角色资源关系
		int count = resourceService.modifyRoleResources(role,resIds);
		if (count > 0) {
			result.put("code", AuthConstants.EDIT_RESULT.SUCCESS.getCode());
			result.put("msg", AuthConstants.EDIT_RESULT.SUCCESS.getMsg());
			return result;
		} else {
			result.put("code", AuthConstants.EDIT_RESULT.FAILED.getCode());
			result.put("msg", AuthConstants.EDIT_RESULT.FAILED.getMsg());
			return result;
		}
	}

}
